Micron Document
<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Closure (computer programming)</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Closure_(computer_programming)"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Closure_computer_programming rootpage-Closure_computer_programming skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Closure (computer programming)</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<style data-mw-deduplicate="TemplateStyles:r1236090951">
/* start https://en.wikipedia.org/ */


.mw-parser-output .hatnote{font-style:italic}.mw-parser-output div.hatnote{padding-left:1.6em;margin-bottom:0.5em}.mw-parser-output .hatnote i{font-style:normal}.mw-parser-output .hatnote+link+.hatnote{margin-top:-0.5em}@media print{body.ns-0 .mw-parser-output .hatnote{display:none!important}}


/* end https://en.wikipedia.org/ */
</style><div role="note" class="hatnote navigation-not-searchable">For other uses, see <a href="Closure_(mathematics)" title="Closure (mathematics)">Closure (mathematics)</a> and <a href="Closure_(disambiguation)" class="mw-redirect mw-disambig" title="Closure (disambiguation)">Closure (disambiguation)</a>.</div>
<div role="note" class="hatnote navigation-not-searchable">Not to be confused with the programming language <a href="Clojure" title="Clojure">Clojure</a>.</div>
<p>
In <a href="Programming_language" title="Programming language">programming languages</a>, a <b>closure</b>, also <b>lexical closure</b> or <b>function closure</b>, is a technique for implementing <a href="Lexically_scoped" class="mw-redirect" title="Lexically scoped">lexically scoped</a> <a href="Name_binding" title="Name binding">name binding</a> in a language with <a href="First-class_function" title="First-class function">first-class functions</a>. <a href="Operational_semantics" title="Operational semantics">Operationally</a>, a closure is a <a href="Record_(computer_science)" title="Record (computer science)">record</a> storing a <a href="Function_(computer_science)" class="mw-redirect" title="Function (computer science)">function</a><sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>a<span class="cite-bracket">]</span></a></sup> together with an environment.<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> The environment is a mapping associating each <a href="Free_variable" class="mw-redirect" title="Free variable">free variable</a> of the function (variables that are used locally, but defined in an enclosing scope) with the <a href="Value_(computer_science)" title="Value (computer science)">value</a> or <a href="Reference_(computer_science)" title="Reference (computer science)">reference</a> to which the name was bound when the closure was created.<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span class="cite-bracket">[</span>b<span class="cite-bracket">]</span></a></sup> Unlike a plain function, a closure allows the function to access those <i>captured variables</i> through the closure's copies of their values or references, even when the function is invoked outside their scope.
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="History_and_etymology">History and etymology</h2></div>
<p>The concept of closures was developed in the 1960s for the mechanical evaluation of expressions in the <a href="%CE%9B-calculus" class="mw-redirect" title="Λ-calculus">λ-calculus</a> and was first fully implemented in 1970 as a language feature in the <a href="PAL_(programming_language)" title="PAL (programming language)">PAL programming language</a> to support lexically scoped <a href="First-class_function" title="First-class function">first-class functions</a>.<sup id="cite_ref-dat2012_4-0" class="reference"><a href="#cite_note-dat2012-4"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup>
</p><p><a href="Peter_Landin" title="Peter Landin">Peter Landin</a> defined the term <i>closure</i> in 1964 as having an <i>environment part</i> and a <i>control part</i> as used by his <a href="SECD_machine" title="SECD machine">SECD machine</a> for evaluating expressions.<sup id="cite_ref-landin_5-0" class="reference"><a href="#cite_note-landin-5"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup> <a href="Joel_Moses" title="Joel Moses">Joel Moses</a> credits Landin with introducing the term <i>closure</i> to refer to a <a href="Anonymous_function" title="Anonymous function">lambda expression</a> with open bindings (free variables) that have been closed by (or bound in) the lexical environment, resulting in a <i>closed expression</i>, or closure.<sup id="cite_ref-6" class="reference"><a href="#cite_note-6"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-7" class="reference"><a href="#cite_note-7"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup> This use was subsequently adopted by <a href="Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman</a> and <a href="Guy_L._Steele_Jr." title="Guy L. Steele Jr.">Steele</a> when they defined <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a> in 1975,<sup id="cite_ref-8" class="reference"><a href="#cite_note-8"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup> a lexically scoped variant of <a href="Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a>, and became widespread.
</p><p>Sussman and <a href="Harold_Abelson" class="mw-redirect" title="Harold Abelson">Abelson</a> also use the term <i>closure</i> in the 1980s with a second, unrelated meaning: the property of an operator that adds data to a <a href="Data_structure" title="Data structure">data structure</a> to also be able to add nested data structures. This use of the term comes from <a href="Closure_(mathematics)" title="Closure (mathematics)">mathematics use</a>, rather than the prior use in computer science. The authors consider this overlap in terminology to be "unfortunate."<sup id="cite_ref-9" class="reference"><a href="#cite_note-9"><span class="cite-bracket">[</span>7<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-heading mw-heading2"><h2 id="Anonymous_functions">Anonymous functions</h2></div>
<div role="note" class="hatnote navigation-not-searchable">Further information: <a href="Anonymous_function" title="Anonymous function">Anonymous function</a></div>
<p>The term <i>closure</i> is often used as a synonym for <a href="Anonymous_function" title="Anonymous function">anonymous function</a>, though strictly, an anonymous function is a function <a href="Literal_(computer_programming)" title="Literal (computer programming)">literal</a> without a name, while a closure is an instance of a function, a <a href="Value_(computer_science)" title="Value (computer science)">value</a>, whose non-local variables have been bound either to values or to <a href="Variable_(computer_science)" title="Variable (computer science)">storage locations</a> (depending on the language; see the <a href="#Lexical_environment">lexical environment</a> section below).
</p><p>For example, in the following <a href="Python_(programming_language)" title="Python (programming language)">Python</a> code:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">(</span><span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
<span class="k">return</span> <span class="n">g</span> <span class="c1"># Return a closure.</span>

<span class="k">def</span><span class="w"> </span><span class="nf">h</span><span class="p">(</span><span class="n">x</span><span class="p">):</span>
<span class="k">return</span> <span class="k">lambda</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span> <span class="c1"># Return a closure.</span>

<span class="c1"># Assigning specific closures to variables.</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
<span class="n">b</span> <span class="o">=</span> <span class="n">h</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

<span class="c1"># Using the closures stored in variables.</span>
<span class="k">assert</span> <span class="n">a</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span>
<span class="k">assert</span> <span class="n">b</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span>

<span class="c1"># Using closures without binding them to variables first.</span>
<span class="k">assert</span> <span class="n">f</span><span class="p">(</span><span class="mi">1</span><span class="p">)(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span> <span class="c1"># f(1) is the closure.</span>
<span class="k">assert</span> <span class="n">h</span><span class="p">(</span><span class="mi">1</span><span class="p">)(</span><span class="mi">5</span><span class="p">)</span> <span class="o">==</span> <span class="mi">6</span> <span class="c1"># h(1) is the closure.</span>
</pre></div>
<p>the values of <code>a</code> and <code>b</code> are closures, in both cases produced by returning a <a href="Nested_function" title="Nested function">nested function</a> with a free variable from the enclosing function, so that the free variable binds to the value of parameter <code>x</code> of the enclosing function. The closures in <code>a</code> and <code>b</code> are functionally identical. The only difference in implementation is that in the first case we used a nested function with a name, <code>g</code>, while in the second case we used an anonymous nested function (using the Python keyword <code>lambda</code> for creating an anonymous function). The original name, if any, used in defining them is irrelevant.
</p><p>A closure is a value like any other value. It does not need to be assigned to a variable and can instead be used directly, as shown in the last two lines of the example. This usage may be deemed an "anonymous closure".
</p><p>The nested function definitions are not themselves closures: they have a free variable which is not yet bound. Only once the enclosing function is evaluated with a value for the parameter is the free variable of the nested function bound, creating a closure, which is then returned from the enclosing function.
</p><p>Lastly, a closure is only distinct from a function with free variables when outside of the scope of the non-local variables, otherwise the defining environment and the execution environment coincide and there is nothing to distinguish these (static and dynamic binding cannot be distinguished because the names resolve to the same values). For example, in the program below, functions with a free variable <code>x</code> (bound to the non-local variable <code>x</code> with global scope) are executed in the same environment where <code>x</code> is defined, so it is immaterial whether these are actually closures:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">x</span> <span class="o">=</span> <span class="mi">1</span>
<span class="n">nums</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]</span>

<span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">(</span><span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>

<span class="nb">map</span><span class="p">(</span><span class="n">f</span><span class="p">,</span> <span class="n">nums</span><span class="p">)</span>
<span class="nb">map</span><span class="p">(</span><span class="k">lambda</span> <span class="n">y</span><span class="p">:</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span><span class="p">,</span> <span class="n">nums</span><span class="p">)</span>
</pre></div>
<p>This is most often achieved by a function return, since the function must be defined within the scope of the non-local variables, in which case typically its own scope will be smaller.
</p><p>This can also be achieved by <a href="Variable_shadowing" title="Variable shadowing">variable shadowing</a> (which reduces the scope of the <a href="Non-local_variable" title="Non-local variable">non-local variable</a>), though this is less common in practice, as it is less useful and shadowing is discouraged. In this example <code>f</code> can be seen to be a closure because <code>x</code> in the body of <code>f</code> is bound to the <code>x</code> in the global namespace, not the <code>x</code> local to <code>g</code>:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">x</span> <span class="o">=</span> <span class="mi">0</span>

<span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">(</span><span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>

<span class="k">def</span><span class="w"> </span><span class="nf">g</span><span class="p">(</span><span class="n">z</span><span class="p">):</span>
<span class="n">x</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># local x shadows global x</span>
<span class="k">return</span> <span class="n">f</span><span class="p">(</span><span class="n">z</span><span class="p">)</span>

<span class="n">g</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="c1"># evaluates to 1, not 2</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="Applications">Applications</h2></div>
<p>The use of closures is associated with languages where functions are <a href="First-class_object" class="mw-redirect" title="First-class object">first-class objects</a>, in which functions can be returned as results from <a href="Higher-order_function" title="Higher-order function">higher-order functions</a>, or passed as arguments to other function calls; if functions with free variables are first-class, then returning one creates a closure. This includes <a href="Functional_programming" title="Functional programming">functional programming</a> languages such as <a href="Lisp_(programming_language)" title="Lisp (programming language)">Lisp</a> and <a href="ML_(programming_language)" title="ML (programming language)">ML</a>, and many modern, multi-paradigm languages, such as <a href="Julia_(programming_language)" title="Julia (programming language)">Julia</a>, <a href="Python_(programming_language)" title="Python (programming language)">Python</a>, and <a href="Rust_(programming_language)" title="Rust (programming language)">Rust</a>. Closures are also often used with <a href="Callback_(computer_programming)" title="Callback (computer programming)">callbacks</a>, particularly for <a href="Event_handler" class="mw-redirect" title="Event handler">event handlers</a>, such as in <a href="JavaScript" title="JavaScript">JavaScript</a>, where they are used for interactions with a <a href="Dynamic_web_page" title="Dynamic web page">dynamic web page</a>.
</p><p>Closures can also be used in a <a href="Continuation-passing_style" title="Continuation-passing style">continuation-passing style</a> to <a href="Information_hiding" title="Information hiding">hide state</a>. Constructs such as <a href="Object_(computer_science)" title="Object (computer science)">objects</a> and <a href="Control_structure" class="mw-redirect" title="Control structure">control structures</a> can thus be implemented with closures. In some languages, a closure may occur when a function is defined within another function, and the inner function refers to local variables of the outer function. At <a href="Run_time_(program_lifecycle_phase)" class="mw-redirect" title="Run time (program lifecycle phase)">run-time</a>, when the outer function executes, a closure is formed, consisting of the inner function's code and references (the upvalues) to any variables of the outer function required by the closure.
</p>
<div class="mw-heading mw-heading3"><h3 id="First-class_functions">First-class functions</h3></div>
<div role="note" class="hatnote navigation-not-searchable">Further information: <a href="First-class_function" title="First-class function">First-class function</a></div>
<p>Closures typically appear in languages with <a href="First-class_object" class="mw-redirect" title="First-class object">first-class functions</a>—in other words, such languages enable functions to be passed as arguments, returned from function calls, bound to variable names, etc., just like simpler types such as strings and integers. For example, consider the following <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a> function:
</p>
<div class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" dir="ltr"><pre><span class="c1">; Return a list of all books with at least THRESHOLD copies sold.</span>
<span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">best-selling-books</span><span class="w"> </span><span class="nv">threshold</span><span class="p">)</span>
<span class="w"> </span><span class="p">(</span><span class="nb">filter</span>
<span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">book</span><span class="p">)</span>
<span class="w"> </span><span class="p">(</span><span class="nb">&gt;=</span><span class="w"> </span><span class="p">(</span><span class="nf">book-sales</span><span class="w"> </span><span class="nv">book</span><span class="p">)</span><span class="w"> </span><span class="nv">threshold</span><span class="p">))</span>
<span class="w"> </span><span class="nv">book-list</span><span class="p">))</span>
</pre></div>
<p>In this example, the <a href="Lambda_(programming)" class="mw-redirect" title="Lambda (programming)">lambda expression</a> <code>(lambda (book) (&gt;= (book-sales book) threshold))</code> appears within the function <code>best-selling-books</code>. When the lambda expression is evaluated, Scheme creates a closure consisting of the code for the lambda expression and a reference to the <code>threshold</code> variable, which is a <a href="Free_variable" class="mw-redirect" title="Free variable">free variable</a> inside the lambda expression.
</p><p>The closure is then passed to the <code>filter</code> function, which calls it repeatedly to determine which books are to be added to the result list and which are to be discarded. Because the closure has a reference to <code>threshold</code>, it can use that variable each time <code>filter</code> calls it. The function <code>filter</code> might be defined in a separate file.
</p><p>Here is the same example rewritten in <a href="JavaScript" title="JavaScript">JavaScript</a>, another popular language with support for closures:
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="c1">// Return a list of all books with at least 'threshold' copies sold.</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">bestSellingBooks</span><span class="p">(</span><span class="nx">threshold</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">bookList</span><span class="p">.</span><span class="nx">filter</span><span class="p">(</span><span class="nx">book</span><span class="w"> </span><span class="p">=&gt;</span><span class="w"> </span><span class="nx">book</span><span class="p">.</span><span class="nx">sales</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="nx">threshold</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
<p>The arrow operator <code>=&gt;</code> is used to define an <a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function expression</a>, and an <code>Array.filter</code> method<sup id="cite_ref-10" class="reference"><a href="#cite_note-10"><span class="cite-bracket">[</span>8<span class="cite-bracket">]</span></a></sup> instead of a global <code>filter</code> function, but otherwise the structure and the effect of the code are the same.
</p><p>A function may create a closure and return it, as in this example:
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="c1">// Return a function that approximates the derivative of f</span>
<span class="c1">// using an interval of dx, which should be appropriately small.</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">derivative</span><span class="p">(</span><span class="nx">f</span><span class="p">,</span><span class="w"> </span><span class="nx">dx</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="w"> </span><span class="p">=&gt;</span><span class="w"> </span><span class="p">(</span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">dx</span><span class="p">)</span><span class="w"> </span><span class="o">-</span><span class="w"> </span><span class="nx">f</span><span class="p">(</span><span class="nx">x</span><span class="p">))</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="nx">dx</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>Because the closure in this case outlives the execution of the function that creates it, the variables <code>f</code> and <code>dx</code> live on after the function <code>derivative</code> returns, even though execution has left their scope and they are no longer visible. In languages without closures, the lifetime of an automatic local variable coincides with the execution of the stack frame where that variable is declared. In languages with closures, variables must continue to exist as long as any existing closures have references to them. This is most commonly implemented using some form of <a href="Garbage_collection_(computer_science)" title="Garbage collection (computer science)">garbage collection</a>.
</p>
<div class="mw-heading mw-heading3"><h3 id="State_representation">State representation</h3></div>
<p>A closure can be used to associate a function with a set of "<a href="Class_(computer_programming)" title="Class (computer programming)">private</a>" variables, which persist over several invocations of the function. The <a href="Scope_(programming)" class="mw-redirect" title="Scope (programming)">scope</a> of the variable encompasses only the closed-over function, so it cannot be accessed from other program code. These are analogous to <a href="Private_variable" class="mw-redirect" title="Private variable">private variables</a> in <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a>, and in fact closures are similar to stateful <a href="Function_objects" class="mw-redirect" title="Function objects">function objects</a> (or functors) with a single call-operator method.
</p><p>In stateful languages, closures can thus be used to implement paradigms for state representation and <a href="Information_hiding" title="Information hiding">information hiding</a>, since the closure's upvalues (its closed-over variables) are of indefinite <a href="Variable_(programming)" class="mw-redirect" title="Variable (programming)">extent</a>, so a value established in one invocation remains available in the next. Closures used in this way no longer have <a href="Referential_transparency" title="Referential transparency">referential transparency</a>, and are thus no longer <a href="Pure_function" title="Pure function">pure functions</a>; nevertheless, they are commonly used in impure functional languages such as <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>.
</p>
<div class="mw-heading mw-heading3"><h3 id="Other_uses">Other uses</h3></div>
<p>Closures have many uses:
</p>
<ul><li>Because closures delay evaluation—i.e., they do not "do" anything until they are called—they can be used to define control structures. For example, all of <a href="Smalltalk" title="Smalltalk">Smalltalk</a>'s standard control structures, including branches (if/then/else) and loops (while and for), are defined using objects whose methods accept closures. Users can easily define their own control structures also.</li>
<li>In languages which implement assignment, multiple functions can be produced that close over the same environment, enabling them to communicate privately by altering that environment. In Scheme:</li></ul>
<div class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" dir="ltr"><pre><span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="nv">foo</span><span class="w"> </span><span class="no">#f</span><span class="p">)</span>
<span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="nv">bar</span><span class="w"> </span><span class="no">#f</span><span class="p">)</span>

<span class="p">(</span><span class="k">let</span><span class="w"> </span><span class="p">((</span><span class="nf">secret-message</span><span class="w"> </span><span class="s">"none"</span><span class="p">))</span>
<span class="w"> </span><span class="p">(</span><span class="k">set!</span><span class="w"> </span><span class="nv">foo</span><span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">msg</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="k">set!</span><span class="w"> </span><span class="nv">secret-message</span><span class="w"> </span><span class="nv">msg</span><span class="p">)))</span>
<span class="w"> </span><span class="p">(</span><span class="k">set!</span><span class="w"> </span><span class="nv">bar</span><span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">()</span><span class="w"> </span><span class="nv">secret-message</span><span class="p">)))</span>

<span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints "none"</span>
<span class="p">(</span><span class="nb">newline</span><span class="p">)</span>
<span class="p">(</span><span class="nf">foo</span><span class="w"> </span><span class="s">"meet me by the docks at midnight"</span><span class="p">)</span>
<span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints "meet me by the docks at midnight"</span>
</pre></div>
<ul><li>Closures can be used to implement <a href="Object-oriented_programming" title="Object-oriented programming">object</a> systems.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11"><span class="cite-bracket">[</span>9<span class="cite-bracket">]</span></a></sup></li></ul>
<p>Note: Some speakers call any data structure that binds a <a href="Scope_(programming)" class="mw-redirect" title="Scope (programming)">lexical</a> environment a closure, but the term usually refers specifically to functions.
</p>
<div class="mw-heading mw-heading2"><h2 id="Implementation_and_theory">Implementation and theory</h2></div>
<p>Closures are typically implemented with a special <a href="Data_structure" title="Data structure">data structure</a> that contains a <a href="Function_pointer" title="Function pointer">pointer to the function code</a>, plus a representation of the function's lexical environment (i.e., the set of available variables) at the time when the closure was created. The referencing environment <a href="Name_binding" title="Name binding">binds</a> the non-local names to the corresponding variables in the lexical environment at the time the closure is created, additionally extending their lifetime to at least as long as the lifetime of the closure. When the closure is entered at a later time, possibly with a different lexical environment, the function is executed with its non-local variables referring to the ones captured by the closure, not the current environment.
</p><p>A language implementation cannot easily support full closures if its run-time memory model allocates all <a href="Automatic_variable" title="Automatic variable">automatic variables</a> on a linear <a href="Stack-based_memory_allocation" title="Stack-based memory allocation">stack</a>. In such languages, a function's automatic local variables are deallocated when the function returns. However, a closure requires that the free variables it references survive the enclosing function's execution. Therefore, those variables must be allocated so that they persist until no longer needed, typically via <a href="Heap_allocation" class="mw-redirect" title="Heap allocation">heap allocation</a>, rather than on the stack, and their lifetime must be managed so they survive until all closures referencing them are no longer in use.
</p><p>This explains why, typically, languages that natively support closures also use <a href="Garbage_collection_(computer_science)" title="Garbage collection (computer science)">garbage collection</a>. The alternatives are manual memory management of non-local variables (explicitly allocating on the heap and freeing when done), or, if using stack allocation, for the language to accept that certain use cases will lead to <a href="Undefined_behaviour" class="mw-redirect" title="Undefined behaviour">undefined behaviour</a>, due to <a href="Dangling_pointer" title="Dangling pointer">dangling pointers</a> to freed automatic variables, as in lambda expressions in C++11<sup id="cite_ref-12" class="reference"><a href="#cite_note-12"><span class="cite-bracket">[</span>10<span class="cite-bracket">]</span></a></sup> or nested functions in GNU C.<sup id="cite_ref-13" class="reference"><a href="#cite_note-13"><span class="cite-bracket">[</span>11<span class="cite-bracket">]</span></a></sup> The <a href="Funarg_problem" title="Funarg problem">funarg problem</a> (or "functional argument" problem) describes the difficulty of implementing functions as first class objects in a stack-based programming language such as C or C++. Similarly in <a href="D_(programming_language)" title="D (programming language)">D</a> version 1, it is assumed that the programmer knows what to do with <a href="Delegation_(programming)" class="mw-redirect" title="Delegation (programming)">delegates</a> and automatic local variables, as their references will be invalid after return from its definition scope (automatic local variables are on the stack) – this still permits many useful functional patterns, but for complex cases needs explicit <a href="Heap_allocation" class="mw-redirect" title="Heap allocation">heap allocation</a> for variables. D version 2 solved this by detecting which variables must be stored on the heap, and performs automatic allocation. Because D uses garbage collection, in both versions, there is no need to track usage of variables as they are passed.
</p><p>In strict functional languages with immutable data (<i>e.g.</i> <a href="Erlang_(programming_language)" title="Erlang (programming language)">Erlang</a>), it is very easy to implement automatic memory management (garbage collection), as there are no possible cycles in variables' references. For example, in Erlang, all arguments and variables are allocated on the heap, but references to them are additionally stored on the stack. After a function returns, references are still valid. Heap cleaning is done by incremental garbage collector.
</p><p>In ML, local variables are lexically scoped, and hence define a stack-like model, but since they are bound to values and not to objects, an implementation is free to copy these values into the closure's data structure in a way that is invisible to the programmer.
</p><p><a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>, which has an <a href="ALGOL" title="ALGOL">ALGOL</a>-like lexical scope system with dynamic variables and garbage collection, lacks a stack programming model and does not suffer from the limitations of stack-based languages. Closures are expressed naturally in Scheme. The lambda form encloses the code, and the free variables of its environment persist within the program as long as they can possibly be accessed, and so they can be used as freely as any other Scheme expression.
</p><p>Closures are closely related to Actors in the <a href="Actor_model" title="Actor model">Actor model</a> of concurrent computation where the values in the function's lexical environment are called <i>acquaintances</i>. An important issue for closures in <a href="Concurrent_programming" class="mw-redirect" title="Concurrent programming">concurrent programming</a> languages is whether the variables in a closure can be updated and, if so, how these updates can be synchronized. Actors provide one solution.<sup id="cite_ref-14" class="reference"><a href="#cite_note-14"><span class="cite-bracket">[</span>12<span class="cite-bracket">]</span></a></sup>
</p><p>Closures are closely related to <a href="Function_object" title="Function object">function objects</a>; the transformation from the former to the latter is known as <a href="Defunctionalization" title="Defunctionalization">defunctionalization</a> or <a href="Lambda_lifting" title="Lambda lifting">lambda lifting</a>; see also <a href="Closure_conversion" class="mw-redirect" title="Closure conversion">closure conversion</a>.
</p>
<div class="mw-heading mw-heading2"><h2 id="Differences_in_semantics">Differences in semantics</h2></div>
<div class="mw-heading mw-heading3"><h3 id="Lexical_environment">Lexical environment</h3></div>
<p>As different languages do not always have a common definition of the lexical environment, their definitions of closure may vary also. The commonly held minimalist definition of the lexical environment defines it as a set of all <a href="Name_binding" title="Name binding">bindings of variables</a> in the scope, and that is also what closures in any language have to capture. However the meaning of a <a href="Variable_(programming)" class="mw-redirect" title="Variable (programming)">variable</a> binding also differs. In imperative languages, variables bind to relative locations in memory that can store values. Although the relative location of a binding does not change at runtime, the value in the bound location can. In such languages, since closure captures the binding, any operation on the variable, whether done from the closure or not, are performed on the same relative memory location. This is often called capturing the variable "by reference". Here is an example illustrating the concept in <a href="ECMAScript" title="ECMAScript">ECMAScript</a>, which is one such language:
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="c1">// Javascript</span>
<span class="kd">var</span><span class="w"> </span><span class="nx">f</span><span class="p">,</span><span class="w"> </span><span class="nx">g</span><span class="p">;</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">foo</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">x</span><span class="p">;</span>
<span class="w"> </span><span class="nx">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">++</span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">};</span>
<span class="w"> </span><span class="nx">g</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">--</span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">};</span>
<span class="w"> </span><span class="nx">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mf">1</span><span class="p">;</span>
<span class="w"> </span><span class="nx">alert</span><span class="p">(</span><span class="s1">'inside foo, call to f(): '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">f</span><span class="p">());</span>
<span class="p">}</span>
<span class="nx">foo</span><span class="p">();</span><span class="w"> </span><span class="c1">// 2</span>
<span class="nx">alert</span><span class="p">(</span><span class="s1">'call to g(): '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">g</span><span class="p">());</span><span class="w"> </span><span class="c1">// 1 (--x)</span>
<span class="nx">alert</span><span class="p">(</span><span class="s1">'call to g(): '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">g</span><span class="p">());</span><span class="w"> </span><span class="c1">// 0 (--x)</span>
<span class="nx">alert</span><span class="p">(</span><span class="s1">'call to f(): '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">f</span><span class="p">());</span><span class="w"> </span><span class="c1">// 1 (++x)</span>
<span class="nx">alert</span><span class="p">(</span><span class="s1">'call to f(): '</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="nx">f</span><span class="p">());</span><span class="w"> </span><span class="c1">// 2 (++x)</span>
</pre></div>
<p>Function <code>foo</code> and the closures referred to by variables <code>f</code> and <code>g</code> all use the same relative memory location signified by local variable <code>x</code>.
</p><p>In some instances the above behaviour may be undesirable, and it is necessary to bind a different lexical closure. Again in ECMAScript, this would be done using the <code>Function.bind()</code>.
</p>
<div class="mw-heading mw-heading3"><h3 id="Example_1:_Reference_to_an_unbound_variable">Example 1: Reference to an unbound variable</h3></div>
<p><sup id="cite_ref-15" class="reference"><a href="#cite_note-15"><span class="cite-bracket">[</span>13<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="kd">var</span><span class="w"> </span><span class="nx">module</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="nx">x</span><span class="o">:</span><span class="w"> </span><span class="mf">42</span><span class="p">,</span>
<span class="w"> </span><span class="nx">getX</span><span class="o">:</span><span class="w"> </span><span class="kd">function</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="k">return</span><span class="w"> </span><span class="k">this</span><span class="p">.</span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
<span class="kd">var</span><span class="w"> </span><span class="nx">unboundGetX</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">module</span><span class="p">.</span><span class="nx">getX</span><span class="p">;</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">unboundGetX</span><span class="p">());</span><span class="w"> </span><span class="c1">// The function gets invoked at the global scope</span>
<span class="c1">// emits undefined as 'x' is not specified in global scope.</span>

<span class="kd">var</span><span class="w"> </span><span class="nx">boundGetX</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nx">unboundGetX</span><span class="p">.</span><span class="nx">bind</span><span class="p">(</span><span class="nx">module</span><span class="p">);</span><span class="w"> </span><span class="c1">// specify object module as the closure</span>
<span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">boundGetX</span><span class="p">());</span><span class="w"> </span><span class="c1">// emits 42</span>
</pre></div>
<div class="mw-heading mw-heading3"><h3 id="Example_2:_Accidental_reference_to_a_bound_variable">Example 2: Accidental reference to a bound variable</h3></div>
<p>For this example the expected behaviour would be that each link should emit its id when clicked; but because the variable 'e' is bound to the scope above, and lazy evaluated on click, what actually happens is that each on click event emits the id of the last element in 'elements' bound at the end of the <a href="For_loop" title="For loop">for loop</a>.<sup id="cite_ref-16" class="reference"><a href="#cite_note-16"><span class="cite-bracket">[</span>14<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="kd">var</span><span class="w"> </span><span class="nx">elements</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">document</span><span class="p">.</span><span class="nx">getElementsByTagName</span><span class="p">(</span><span class="s1">'a'</span><span class="p">);</span>
<span class="c1">// Incorrect: e is bound to the function containing the 'for' loop, not the closure of "handle"</span>
<span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kd">var</span><span class="w"> </span><span class="nx">e</span><span class="w"> </span><span class="k">of</span><span class="w"> </span><span class="nx">elements</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span>
<span class="w"> </span><span class="nx">e</span><span class="p">.</span><span class="nx">onclick</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="kd">function</span><span class="w"> </span><span class="nx">handle</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span>
<span class="w"> </span><span class="nx">alert</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">id</span><span class="p">);</span>
<span class="w"> </span><span class="p">}</span><span class="w"> </span>
<span class="p">}</span>
</pre></div>
<p>Again here variable <code>e</code> would need to be bound by the scope of the block using <code>handle.bind(this)</code> or the <code>let</code> keyword.
</p><p>On the other hand, many functional languages, such as <a href="ML_(programming_language)" title="ML (programming language)">ML</a>, bind variables directly to values. In this case, since there is no way to change the value of the variable once it is bound, there is no need to share the state between closures—they just use the same values. This is often called capturing the variable "by value". Java's local and anonymous classes also fall into this category—they require captured local variables to be <code>final</code>, which also means there is no need to share state.
</p><p>Some languages enable choosing between capturing the value of a variable or its location. For example, in C++11, captured variables are either declared with <code>[&amp;]</code>, which means captured by reference, or with <code>[=]</code>, which means captured by value.
</p><p>Yet another subset, <a href="Lazy_evaluation" title="Lazy evaluation">lazy</a> functional languages such as <a href="Haskell" title="Haskell">Haskell</a>, bind variables to results of future computations rather than values. Consider this example in Haskell:
</p>
<div class="mw-highlight mw-highlight-lang-haskell mw-content-ltr" dir="ltr"><pre><span class="c1">-- Haskell</span>
<span class="nf">foo</span><span class="w"> </span><span class="ow">::</span><span class="w"> </span><span class="kt">Fractional</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">=&gt;</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="p">(</span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">a</span><span class="p">)</span>
<span class="nf">foo</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="n">y</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="p">(</span><span class="nf">\</span><span class="n">z</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">z</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">r</span><span class="p">)</span>
<span class="w"> </span><span class="kr">where</span><span class="w"> </span><span class="n">r</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">/</span><span class="w"> </span><span class="n">y</span>

<span class="nf">f</span><span class="w"> </span><span class="ow">::</span><span class="w"> </span><span class="kt">Fractional</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">=&gt;</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="ow">-&gt;</span><span class="w"> </span><span class="n">a</span>
<span class="nf">f</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="n">foo</span><span class="w"> </span><span class="mi">1</span><span class="w"> </span><span class="mi">0</span>

<span class="nf">main</span><span class="w"> </span><span class="ow">=</span><span class="w"> </span><span class="n">print</span><span class="w"> </span><span class="p">(</span><span class="n">f</span><span class="w"> </span><span class="mi">123</span><span class="p">)</span>
</pre></div>
<p>The binding of <code>r</code> captured by the closure defined within function <code>foo</code> is to the computation <code>(x / y)</code>—which in this case results in division by zero. However, since it is the computation that is captured, and not the value, the error only manifests when the closure is invoked, and then attempts to use the captured binding.
</p>
<div class="mw-heading mw-heading3"><h3 id="Closure_leaving">Closure leaving</h3></div>
<p>Yet more differences manifest themselves in the behavior of other lexically scoped constructs, such as <code>return</code>, <code>break</code> and <code>continue</code> statements. Such constructs can, in general, be considered in terms of invoking an <a href="Escape_continuation" class="mw-redirect" title="Escape continuation">escape continuation</a> established by an enclosing control statement (in case of <code>break</code> and <code>continue</code>, such interpretation requires looping constructs to be considered in terms of recursive function calls). In some languages, such as ECMAScript, <code>return</code> refers to the continuation established by the closure lexically innermost with respect to the statement—thus, a <code>return</code> within a closure transfers control to the code that called it. However, in <a href="Smalltalk" title="Smalltalk">Smalltalk</a>, the superficially similar operator <code>^</code> invokes the escape continuation established for the method invocation, ignoring the escape continuations of any intervening nested closures. The escape continuation of a particular closure can only be invoked in Smalltalk implicitly by reaching the end of the closure's code. These examples in ECMAScript and Smalltalk highlight the difference:
</p>
<div class="mw-highlight mw-highlight-lang-smalltalk mw-content-ltr" dir="ltr"><pre><span class="c">"Smalltalk"</span>
<span class="nf">foo</span>
<span class="o">|</span><span class="nv"> xs </span><span class="o">|</span>
<span class="nv">xs</span> <span class="o">:=</span> <span class="ss">#(</span><span class="m">1</span> <span class="m">2</span> <span class="m">3</span> <span class="m">4</span><span class="ss">)</span><span class="p">.</span>
<span class="nv">xs</span> <span class="nf">do:</span> [<span class="o">:</span><span class="nv">x</span> <span class="o">|</span> <span class="o">^</span><span class="nv">x</span>]<span class="p">.</span>
<span class="o">^</span><span class="m">0</span>
<span class="nf">bar</span>
<span class="nf">Transcript</span> <span class="nf">show:</span> (<span class="bp">self</span> <span class="nf">foo</span> <span class="nf">printString</span>) <span class="c">"prints 1"</span>
</pre></div>
<div class="mw-highlight mw-highlight-lang-javascript mw-content-ltr" dir="ltr"><pre><span class="c1">// ECMAScript</span>
<span class="kd">function</span><span class="w"> </span><span class="nx">foo</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">var</span><span class="w"> </span><span class="nx">xs</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">[</span><span class="mf">1</span><span class="p">,</span><span class="w"> </span><span class="mf">2</span><span class="p">,</span><span class="w"> </span><span class="mf">3</span><span class="p">,</span><span class="w"> </span><span class="mf">4</span><span class="p">];</span>
<span class="w"> </span><span class="nx">xs</span><span class="p">.</span><span class="nx">forEach</span><span class="p">(</span><span class="kd">function</span><span class="w"> </span><span class="p">(</span><span class="nx">x</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="nx">x</span><span class="p">;</span><span class="w"> </span><span class="p">});</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mf">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="nx">alert</span><span class="p">(</span><span class="nx">foo</span><span class="p">());</span><span class="w"> </span><span class="c1">// prints 0</span>
</pre></div>
<p>The above code snippets will behave differently because the Smalltalk <code>^</code> operator and the JavaScript <code>return</code> operator are not analogous. In the ECMAScript example, <code>return x</code> will leave the inner closure to begin a new iteration of the <code>forEach</code> loop, whereas in the Smalltalk example, <code>^x</code> will abort the loop and return from the method <code>foo</code>.
</p><p><a href="Common_Lisp" title="Common Lisp">Common Lisp</a> provides a construct that can express either of the above actions: Lisp <code>(return-from foo x)</code> behaves as <a href="Smalltalk" title="Smalltalk">Smalltalk</a> <code>^x</code>, while Lisp <code>(return-from nil x)</code> behaves as <a href="JavaScript" title="JavaScript">JavaScript</a> <code>return x</code>. Hence, Smalltalk makes it possible for a captured escape continuation to outlive the extent in which it can be successfully invoked. Consider:
</p>
<div class="mw-highlight mw-highlight-lang-smalltalk mw-content-ltr" dir="ltr"><pre><span class="c">"Smalltalk"</span>
<span class="nf">foo</span>
<span class="o">^</span>[ <span class="o">:</span><span class="nv">x</span> <span class="o">|</span> <span class="o">^</span><span class="nv">x</span> ]
<span class="nf">bar</span>
<span class="nf">|</span> <span class="nv">f</span> <span class="nf">|</span>
<span class="nv">f</span> <span class="o">:=</span> <span class="bp">self</span> <span class="nf">foo</span><span class="p">.</span>
<span class="nv">f</span> <span class="nf">value:</span> <span class="m">123</span> <span class="c">"error!"</span>
</pre></div>
<p>When the closure returned by the method <code>foo</code> is invoked, it attempts to return a value from the invocation of <code>foo</code> that created the closure. Since that call has already returned and the Smalltalk method invocation model does not follow the <a href="Spaghetti_stack" class="mw-redirect" title="Spaghetti stack">spaghetti stack</a> discipline to facilitate multiple returns, this operation results in an error.
</p><p>Some languages, such as <a href="Ruby_(programming_language)" title="Ruby (programming language)">Ruby</a>, enable the programmer to choose the way <code>return</code> is captured. An example in Ruby:
</p>
<div class="mw-highlight mw-highlight-lang-ruby mw-content-ltr" dir="ltr"><pre><span class="c1"># Ruby</span>

<span class="c1"># Closure using a Proc</span>
<span class="k">def</span><span class="w"> </span><span class="nf">foo</span>
<span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="no">Proc</span><span class="o">.</span><span class="n">new</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">"return from foo from inside proc"</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="n">f</span><span class="o">.</span><span class="n">call</span><span class="w"> </span><span class="c1"># control leaves foo here</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">"return from foo"</span>
<span class="k">end</span>

<span class="c1"># Closure using a lambda</span>
<span class="k">def</span><span class="w"> </span><span class="nf">bar</span>
<span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="nb">lambda</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">"return from lambda"</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="n">f</span><span class="o">.</span><span class="n">call</span><span class="w"> </span><span class="c1"># control does not leave bar here</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="s2">"return from bar"</span>
<span class="k">end</span>

<span class="nb">puts</span><span class="w"> </span><span class="n">foo</span><span class="w"> </span><span class="c1"># prints "return from foo from inside proc"</span>
<span class="nb">puts</span><span class="w"> </span><span class="n">bar</span><span class="w"> </span><span class="c1"># prints "return from bar"</span>
</pre></div>
<p>Both <code>Proc.new</code> and <code>lambda</code> in this example are ways to create a closure, but semantics of the closures thus created are different with respect to the <code>return</code> statement.
</p><p>In <a href="Scheme_(programming_language)" title="Scheme (programming language)">Scheme</a>, definition and scope of the <code>return</code> control statement is explicit (and only arbitrarily named 'return' for the sake of the example). The following is a direct translation of the Ruby sample.
</p>
<div class="mw-highlight mw-highlight-lang-scheme mw-content-ltr" dir="ltr"><pre><span class="c1">; Scheme</span>
<span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="nb">call/cc</span><span class="w"> </span><span class="nb">call-with-current-continuation</span><span class="p">)</span>

<span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">foo</span><span class="p">)</span>
<span class="w"> </span><span class="p">(</span><span class="nb">call/cc</span>
<span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="p">)</span>
<span class="w"> </span><span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">"return from foo from inside proc"</span><span class="p">))</span>
<span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="c1">; control leaves foo here</span>
<span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">"return from foo"</span><span class="p">))))</span>

<span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">)</span>
<span class="w"> </span><span class="p">(</span><span class="nb">call/cc</span>
<span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="p">)</span>
<span class="w"> </span><span class="p">(</span><span class="k">define</span><span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nb">call/cc</span><span class="w"> </span><span class="p">(</span><span class="k">lambda</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="p">)</span><span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">"return from lambda"</span><span class="p">))))</span>
<span class="w"> </span><span class="p">(</span><span class="nf">f</span><span class="p">)</span><span class="w"> </span><span class="c1">; control does not leave bar here</span>
<span class="w"> </span><span class="p">(</span><span class="nf">return</span><span class="w"> </span><span class="s">"return from bar"</span><span class="p">))))</span>

<span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">foo</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints "return from foo from inside proc"</span>
<span class="p">(</span><span class="nb">newline</span><span class="p">)</span>
<span class="p">(</span><span class="nb">display</span><span class="w"> </span><span class="p">(</span><span class="nf">bar</span><span class="p">))</span><span class="w"> </span><span class="c1">; prints "return from bar"</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="Closure-like_constructs">Closure-like constructs</h2></div>
<p>Some languages have features which simulate the behavior of closures. In languages such as <a href="C%2B%2B" title="C++">C++</a>, <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a>, <a href="D_(programming_language)" title="D (programming language)">D</a>, <a href="Java_(programming_language)" title="Java (programming language)">Java</a>, <a href="Objective-C" title="Objective-C">Objective-C</a>, and <a href="Visual_Basic_(.NET)" title="Visual Basic (.NET)">Visual Basic (.NET)</a> (VB.NET), these features are the result of the language's object-oriented paradigm.
</p>
<div class="mw-heading mw-heading3"><h3 id="Callbacks_(C)">Callbacks (C)</h3></div>
<p>Some <a href="C_(programming_language)" title="C (programming language)">C</a> libraries support <a href="Callback_(computer_programming)" title="Callback (computer programming)">callbacks</a>. This is sometimes implemented by providing two values when registering the callback with the library: a function pointer and a separate <code>void*</code> pointer to arbitrary data of the user's choice. When the library executes the callback function, it passes along the data pointer. This enables the callback to maintain state and to refer to information captured at the time it was registered with the library. The idiom is similar to closures in functionality, but not in syntax. The <code>void*</code> pointer is not <a href="Type_safety" title="Type safety">type safe</a> so this C idiom differs from type-safe closures in C#, Haskell or ML.
</p><p>Callbacks are used extensively in <a href="Graphical_user_interface" title="Graphical user interface">graphical user interface</a> (GUI) <a href="Widget_toolkit" title="Widget toolkit">widget toolkits</a> to implement <a href="Event-driven_programming" title="Event-driven programming">event-driven programming</a> by associating general functions of graphical widgets (menus, buttons, check boxes, sliders, spinners, etc.) with application-specific functions implementing the specific desired behavior for the application.
</p>
<div class="mw-heading mw-heading4"><h4 id="Nested_function_and_function_pointer_(C)">Nested function and function pointer (C)</h4></div>
<p>With a <a href="GNU_Compiler_Collection" title="GNU Compiler Collection">GNU Compiler Collection</a> (GCC) extension, a nested function<sup id="cite_ref-17" class="reference"><a href="#cite_note-17"><span class="cite-bracket">[</span>15<span class="cite-bracket">]</span></a></sup> can be used and a function pointer can emulate closures, provided the function does not exit the containing scope. The next example is invalid because <code>adder</code> is a top-level definition (depending on compiler version, it could produce a correct result if compiled with no optimizing, i.e., at <code>-O0</code>):
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;stdio.h&gt;</span>

<span class="k">typedef</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">fn_int_to_int</span><span class="p">)(</span><span class="kt">int</span><span class="p">);</span><span class="w"> </span><span class="c1">// type of function int-&gt;int</span>

<span class="n">fn_int_to_int</span><span class="w"> </span><span class="nf">adder</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">number</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">add</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">value</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">number</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="o">&amp;</span><span class="n">add</span><span class="p">;</span><span class="w"> </span><span class="c1">// &amp; operator is optional here because the name of a function in C is a pointer pointing on itself</span>
<span class="p">}</span>

<span class="kt">int</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">fn_int_to_int</span><span class="w"> </span><span class="n">add10</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">adder</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span>
<span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">"%d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">add10</span><span class="p">(</span><span class="mi">1</span><span class="p">));</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>But moving <code>adder</code> (and, optionally, the <code>typedef</code>) in <code>main</code> makes it valid:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="cp">#include</span><span class="w"> </span><span class="cpf">&lt;stdio.h&gt;</span>

<span class="kt">int</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">typedef</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">fn_int_to_int</span><span class="p">)(</span><span class="kt">int</span><span class="p">);</span><span class="w"> </span><span class="c1">// type of function int-&gt;int</span>
<span class="w"> </span>
<span class="w"> </span><span class="n">fn_int_to_int</span><span class="w"> </span><span class="n">adder</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">number</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">add</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">value</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">value</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="n">number</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">add</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span>
<span class="w"> </span><span class="n">fn_int_to_int</span><span class="w"> </span><span class="n">add10</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">adder</span><span class="p">(</span><span class="mi">10</span><span class="p">);</span>
<span class="w"> </span><span class="n">printf</span><span class="p">(</span><span class="s">"%d</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span><span class="w"> </span><span class="n">add10</span><span class="p">(</span><span class="mi">1</span><span class="p">));</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
</pre></div>
<p>If executed this now prints <code>11</code> as expected.
</p>
<div class="mw-heading mw-heading3"><h3 id="Local_classes_and_lambda_functions_(Java)">Local classes and lambda functions (Java)</h3></div>
<p><a href="Java_(programming_language)" title="Java (programming language)">Java</a> enables <a href="Class_(object-oriented_programming)" class="mw-redirect" title="Class (object-oriented programming)">classes</a> to be defined inside <a href="Method_(object-oriented_programming)" class="mw-redirect" title="Method (object-oriented programming)">methods</a>. These are called <i>local classes</i>. When such classes are not named, they are known as <i><a href="Anonymous_class" class="mw-redirect" title="Anonymous class">anonymous classes</a></i> (or anonymous <i>inner</i> classes). A local class (either named or anonymous) may refer to names in lexically enclosing classes, or read-only variables (marked as <code>final</code>) in the lexically enclosing method.
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">class</span> <span class="nc">CalculationWindow</span><span class="w"> </span><span class="kd">extends</span><span class="w"> </span><span class="n">JFrame</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">private</span><span class="w"> </span><span class="kd">volatile</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">result</span><span class="p">;</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">calculateInSeparateThread</span><span class="p">(</span><span class="kd">final</span><span class="w"> </span><span class="n">URI</span><span class="w"> </span><span class="n">uri</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// The expression "new Runnable() { ... }" is an anonymous class implementing the 'Runnable' interface.</span>
<span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Thread</span><span class="p">(</span>
<span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Runnable</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">run</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// It can read final local variables:</span>
<span class="w"> </span><span class="n">calculate</span><span class="p">(</span><span class="n">uri</span><span class="p">);</span>
<span class="w"> </span><span class="c1">// It can access private fields of the enclosing class:</span>
<span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="p">).</span><span class="na">start</span><span class="p">();</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>The capturing of <code>final</code> variables enables capturing variables by value. Even if the variable to capture is non-<code>final</code>, it can always be copied to a temporary <code>final</code> variable just before the class.
</p><p>Capturing of variables by reference can be emulated by using a <code>final</code> reference to a mutable container, for example, a one-element array. The local class will not be able to change the value of the container reference, but it will be able to change the contents of the container.
</p><p>With the advent of Java 8's lambda expressions,<sup id="cite_ref-18" class="reference"><a href="#cite_note-18"><span class="cite-bracket">[</span>16<span class="cite-bracket">]</span></a></sup> the closure causes the above code to be executed as:
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">class</span> <span class="nc">CalculationWindow</span><span class="w"> </span><span class="kd">extends</span><span class="w"> </span><span class="n">JFrame</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">private</span><span class="w"> </span><span class="kd">volatile</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">result</span><span class="p">;</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">calculateInSeparateThread</span><span class="p">(</span><span class="kd">final</span><span class="w"> </span><span class="n">URI</span><span class="w"> </span><span class="n">uri</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// The code () -&gt; { /* code */ } is a closure.</span>
<span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">Thread</span><span class="p">(()</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">calculate</span><span class="p">(</span><span class="n">uri</span><span class="p">);</span>
<span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">+</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span>
<span class="w"> </span><span class="p">}).</span><span class="na">start</span><span class="p">();</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Local classes are one of the types of <a href="Inner_class" title="Inner class">inner class</a> that are declared within the body of a method. Java also supports inner classes that are declared as <i>non-static members</i> of an enclosing class.<sup id="cite_ref-19" class="reference"><a href="#cite_note-19"><span class="cite-bracket">[</span>17<span class="cite-bracket">]</span></a></sup> They are normally referred to just as "inner classes".<sup id="cite_ref-20" class="reference"><a href="#cite_note-20"><span class="cite-bracket">[</span>18<span class="cite-bracket">]</span></a></sup> These are defined in the body of the enclosing class and have full access to instance variables of the enclosing class. Due to their binding to these instance variables, an inner class may only be instantiated with an explicit binding to an instance of the enclosing class using a special syntax.<sup id="cite_ref-21" class="reference"><a href="#cite_note-21"><span class="cite-bracket">[</span>19<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">public</span><span class="w"> </span><span class="kd">class</span> <span class="nc">EnclosingClass</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="cm">/* Define the inner class */</span>
<span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kd">class</span> <span class="nc">InnerClass</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">incrementAndReturnCounter</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">counter</span><span class="o">++</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="p">}</span>

<span class="w"> </span><span class="kd">private</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">counter</span><span class="p">;</span>
<span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">counter</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">0</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>

<span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="nf">getCounter</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">counter</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span>

<span class="w"> </span><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">EnclosingClass</span><span class="w"> </span><span class="n">enclosingClassInstance</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">EnclosingClass</span><span class="p">();</span>
<span class="w"> </span><span class="cm">/* Instantiate the inner class, with binding to the instance */</span>
<span class="w"> </span><span class="n">EnclosingClass</span><span class="p">.</span><span class="na">InnerClass</span><span class="w"> </span><span class="n">innerClassInstance</span><span class="w"> </span><span class="o">=</span>
<span class="w"> </span><span class="n">enclosingClassInstance</span><span class="p">.</span><span class="na">new</span><span class="w"> </span><span class="nf">InnerClass</span><span class="p">();</span>

<span class="w"> </span><span class="k">for</span><span class="w"> </span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">enclosingClassInstance</span><span class="p">.</span><span class="na">getCounter</span><span class="p">();</span>
<span class="w"> </span><span class="p">(</span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">innerClassInstance</span><span class="p">.</span><span class="na">incrementAndReturnCounter</span><span class="p">())</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="mi">10</span><span class="p">;</span>
<span class="w"> </span><span class="cm">/* increment step omitted */</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
<span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="p">}</span>
<span class="p">}</span>
</pre></div>
<p>Upon execution, this will print the integers from 0 to 9. Beware to not confuse this type of class with the nested class, which is declared in the same way with an accompanied usage of the "static" modifier; those have not the desired effect but are instead just classes with no special binding defined in an enclosing class.
</p><p>As of <a href="Java_version_history#Java_8" title="Java version history">Java 8</a>, Java supports functions as first class objects. Lambda expressions of this form are considered of type <code>Function&lt;T,U&gt;</code> with T being the domain and U the image type. The expression can be called with its <code>.apply(T t)</code> method, but not with a standard method call.
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="kd">public</span><span class="w"> </span><span class="kd">static</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="nf">main</span><span class="p">(</span><span class="n">String</span><span class="o">[]</span><span class="w"> </span><span class="n">args</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="n">Function</span><span class="o">&lt;</span><span class="n">String</span><span class="p">,</span><span class="w"> </span><span class="n">Integer</span><span class="o">&gt;</span><span class="w"> </span><span class="n">length</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">s</span><span class="w"> </span><span class="o">-&gt;</span><span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="na">length</span><span class="p">();</span>

<span class="w"> </span><span class="n">System</span><span class="p">.</span><span class="na">out</span><span class="p">.</span><span class="na">println</span><span class="p">(</span><span class="w"> </span><span class="n">length</span><span class="p">.</span><span class="na">apply</span><span class="p">(</span><span class="s">"Hello, world!"</span><span class="p">)</span><span class="w"> </span><span class="p">);</span><span class="w"> </span><span class="c1">// Will print 13.</span>
<span class="p">}</span>
</pre></div>
<div class="mw-heading mw-heading3"><h3 id="Blocks_(C,_C++,_Objective-C_2.0)">Blocks (C, C++, Objective-C 2.0)</h3></div>
<div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Blocks_(C_language_extension)" title="Blocks (C language extension)">Blocks (C language extension)</a></div>
<p><a href="Apple_Inc." title="Apple Inc.">Apple</a> introduced <a href="Blocks_(C_language_extension)" title="Blocks (C language extension)">blocks</a>, a form of closure, as a nonstandard extension into <a href="C_(programming_language)" title="C (programming language)">C</a>, <a href="C%2B%2B" title="C++">C++</a>, <a href="Objective-C_2.0" class="mw-redirect" title="Objective-C 2.0">Objective-C 2.0</a> and in <a href="Mac_OS_X_Snow_Leopard" title="Mac OS X Snow Leopard">Mac OS X 10.6 "Snow Leopard"</a> and <a href="IOS_4" title="IOS 4">iOS 4</a>.0. Apple made their implementation available for the GCC and clang compilers.
</p><p>Pointers to block and block literals are marked with <code>^</code>. Normal local variables are captured by value when the block is created, and are read-only inside the block. Variables to be captured by reference are marked with <code>__block</code>. Blocks that need to persist outside of the scope they are created in may need to be copied.<sup id="cite_ref-22" class="reference"><a href="#cite_note-22"><span class="cite-bracket">[</span>20<span class="cite-bracket">]</span></a></sup><sup id="cite_ref-23" class="reference"><a href="#cite_note-23"><span class="cite-bracket">[</span>21<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-objc mw-content-ltr" dir="ltr"><pre><span class="k">typedef</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="p">(</span><span class="o">^</span><span class="n">IntBlock</span><span class="p">)();</span>

<span class="n">IntBlock</span><span class="w"> </span><span class="nf">downCounter</span><span class="p">(</span><span class="kt">int</span><span class="w"> </span><span class="n">start</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">__block</span><span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">start</span><span class="p">;</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">[[</span><span class="w"> </span><span class="o">^</span><span class="kt">int</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">i</span><span class="o">--</span><span class="p">;</span>
<span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="k">copy</span><span class="p">]</span><span class="w"> </span><span class="n">autorelease</span><span class="p">];</span>
<span class="p">}</span>

<span class="n">IntBlock</span><span class="w"> </span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">downCounter</span><span class="p">(</span><span class="mi">5</span><span class="p">);</span>
<span class="n">NSLog</span><span class="p">(</span><span class="s">@"%d"</span><span class="p">,</span><span class="w"> </span><span class="n">f</span><span class="p">());</span>
<span class="n">NSLog</span><span class="p">(</span><span class="s">@"%d"</span><span class="p">,</span><span class="w"> </span><span class="n">f</span><span class="p">());</span>
<span class="n">NSLog</span><span class="p">(</span><span class="s">@"%d"</span><span class="p">,</span><span class="w"> </span><span class="n">f</span><span class="p">());</span>
</pre></div>
<div class="mw-heading mw-heading3"><h3 id="Delegates_(C#,_VB.NET,_D)">Delegates (C#, VB.NET, D)</h3></div>
<p><a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a> anonymous methods and lambda expressions support closure:
</p>
<div class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><pre><span class="kt">var</span><span class="w"> </span><span class="n">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="p">[]</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">,</span><span class="w"> </span><span class="mi">4</span><span class="p">};</span>
<span class="kt">var</span><span class="w"> </span><span class="n">multiplier</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span><span class="p">;</span>
<span class="kt">var</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">data</span><span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">x</span><span class="w"> </span><span class="o">=&gt;</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">multiplier</span><span class="p">);</span>
</pre></div>
<p><a href="Visual_Basic_.NET" class="mw-redirect" title="Visual Basic .NET">Visual Basic .NET</a>, which has many language features similar to those of C#, also supports lambda expressions with closures:
</p>
<div class="mw-highlight mw-highlight-lang-vb.net mw-content-ltr" dir="ltr"><pre><span class="k">Dim</span><span class="w"> </span><span class="n">data</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="p">{</span><span class="mi">1</span><span class="p">,</span><span class="w"> </span><span class="mi">2</span><span class="p">,</span><span class="w"> </span><span class="mi">3</span><span class="p">,</span><span class="w"> </span><span class="mi">4</span><span class="p">}</span>
<span class="k">Dim</span><span class="w"> </span><span class="n">multiplier</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="mi">2</span>
<span class="k">Dim</span><span class="w"> </span><span class="n">result</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">data</span><span class="p">.</span><span class="n">Select</span><span class="p">(</span><span class="n">Function</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">*</span><span class="w"> </span><span class="n">multiplier</span><span class="p">)</span>
</pre></div>
<p>In <a href="D_(programming_language)" title="D (programming language)">D</a>, closures are implemented by delegates, a function pointer paired with a context pointer (e.g. a class instance, or a stack frame on the heap in the case of closures).
</p>
<div class="mw-highlight mw-highlight-lang-d mw-content-ltr" dir="ltr"><pre><span class="k">auto</span><span class="w"> </span><span class="n">test1</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">7</span><span class="p">;</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="k">delegate</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">+</span><span class="w"> </span><span class="mi">3</span><span class="p">;</span><span class="w"> </span><span class="p">};</span><span class="w"> </span><span class="c1">// anonymous delegate construction</span>
<span class="p">}</span>

<span class="k">auto</span><span class="w"> </span><span class="n">test2</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="mi">20</span><span class="p">;</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">foo</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">a</span><span class="w"> </span><span class="p">+</span><span class="w"> </span><span class="mi">5</span><span class="p">;</span><span class="w"> </span><span class="p">}</span><span class="w"> </span><span class="c1">// inner function</span>
<span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="p">&amp;</span><span class="n">foo</span><span class="p">;</span><span class="w"> </span><span class="c1">// other way to construct delegate</span>
<span class="p">}</span>

<span class="kt">void</span><span class="w"> </span><span class="n">bar</span><span class="p">()</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="k">auto</span><span class="w"> </span><span class="n">dg</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">test1</span><span class="p">();</span>
<span class="w"> </span><span class="n">dg</span><span class="p">();</span><span class="w"> </span><span class="c1">// =10 // ok, test1.a is in a closure and still exists</span>

<span class="w"> </span><span class="n">dg</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="n">test2</span><span class="p">();</span>
<span class="w"> </span><span class="n">dg</span><span class="p">();</span><span class="w"> </span><span class="c1">// =25 // ok, test2.a is in a closure and still exists</span>
<span class="p">}</span>
</pre></div>
<p>D version 1, has limited closure support. For example, the above code will not work correctly, because the variable a is on the stack, and after returning from test(), it is no longer valid to use it (most probably calling foo via dg(), will return a 'random' integer). This can be solved by explicitly allocating the variable 'a' on heap, or using structs or class to store all needed closed variables and construct a delegate from a method implementing the same code. Closures can be passed to other functions, as long as they are only used while the referenced values are still valid (for example calling another function with a closure as a callback parameter), and are useful for writing generic data processing code, so this limitation, in practice, is often not an issue.
</p><p>This limitation was fixed in D version 2 - the variable 'a' will be automatically allocated on the heap because it is used in the inner function, and a delegate of that function can escape the current scope (via assignment to dg or return). Any other local variables (or arguments) that are not referenced by delegates or that are only referenced by delegates that do not escape the current scope, remain on the stack, which is simpler and faster than heap allocation. The same is true for inner's class methods that reference a function's variables.
</p>
<div class="mw-heading mw-heading3"><h3 id="Function_objects_(C++)">Function objects (C++)</h3></div>
<p><a href="C%2B%2B" title="C++">C++</a> enables defining <a href="Function_object" title="Function object">function objects</a> by overloading <code>operator()</code>. These objects behave somewhat like functions in a functional programming language. They may be created at runtime and may contain state, but they do not implicitly capture local variables as closures do. As of <a href="C%2B%2B11" title="C++11">the 2011 revision</a>, the C++ language also supports closures, which are a type of function object constructed automatically from a special <a href="Language_construct" title="Language construct">language construct</a> called <i>lambda-expression</i>. A C++ closure may capture its context either by storing copies of the accessed variables as members of the closure object or by reference. In the latter case, if the closure object escapes the scope of a referenced object, invoking its <code>operator()</code> causes undefined behavior since C++ closures do not extend the lifetime of their context.</p><div role="note" class="hatnote navigation-not-searchable">Main article: <a href="Examples_of_anonymous_functions#C++_(since_C++11)" title="Examples of anonymous functions">Examples_of_anonymous_functions §&nbsp;C++_(since_C++11)</a></div>
<div class="mw-highlight mw-highlight-lang-cpp mw-content-ltr" dir="ltr"><pre><span class="kt">void</span><span class="w"> </span><span class="nf">foo</span><span class="p">(</span><span class="n">string</span><span class="w"> </span><span class="n">myname</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="kt">int</span><span class="w"> </span><span class="n">y</span><span class="p">;</span>
<span class="w"> </span><span class="n">vector</span><span class="o">&lt;</span><span class="n">string</span><span class="o">&gt;</span><span class="w"> </span><span class="n">n</span><span class="p">;</span>
<span class="w"> </span><span class="c1">// ...</span>
<span class="w"> </span><span class="k">auto</span><span class="w"> </span><span class="n">i</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">std</span><span class="o">::</span><span class="n">find_if</span><span class="p">(</span><span class="n">n</span><span class="p">.</span><span class="n">begin</span><span class="p">(),</span><span class="w"> </span><span class="n">n</span><span class="p">.</span><span class="n">end</span><span class="p">(),</span>
<span class="w"> </span><span class="c1">// this is the lambda expression:</span>
<span class="w"> </span><span class="p">[</span><span class="o">&amp;</span><span class="p">](</span><span class="k">const</span><span class="w"> </span><span class="n">string</span><span class="o">&amp;</span><span class="w"> </span><span class="n">s</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="k">return</span><span class="w"> </span><span class="n">s</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="n">myname</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="n">s</span><span class="p">.</span><span class="n">size</span><span class="p">()</span><span class="w"> </span><span class="o">&gt;</span><span class="w"> </span><span class="n">y</span><span class="p">;</span><span class="w"> </span><span class="p">}</span>
<span class="w"> </span><span class="p">);</span>
<span class="w"> </span><span class="c1">// 'i' is now either 'n.end()' or points to the first string in 'n'</span>
<span class="w"> </span><span class="c1">// which is not equal to 'myname' and whose length is greater than 'y'</span>
<span class="p">}</span>
</pre></div>
<div class="mw-heading mw-heading3"><h3 id="Inline_agents_(Eiffel)">Inline agents (Eiffel)</h3></div>
<p><a href="Eiffel_(programming_language)" title="Eiffel (programming language)">Eiffel</a> includes inline agents defining closures. An inline agent is an object representing a routine, defined by giving the code of the routine in-line. For example, in
</p>
<div class="mw-highlight mw-highlight-lang-eiffel mw-content-ltr" dir="ltr"><pre><span class="n">ok_button</span><span class="p">.</span><span class="n">click_event</span><span class="p">.</span><span class="n">subscribe</span><span class="w"> </span><span class="p">(</span>
<span class="w"> </span><span class="kr">agent</span><span class="w"> </span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="n">y</span><span class="p">:</span><span class="w"> </span><span class="nc">INTEGER</span><span class="p">)</span><span class="w"> </span><span class="kr">do</span>
<span class="w"> </span><span class="n">map</span><span class="p">.</span><span class="n">country_at_coordinates</span><span class="w"> </span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="w"> </span><span class="n">y</span><span class="p">).</span><span class="n">display</span>
<span class="w"> </span><span class="kr">end</span>
<span class="p">)</span>
</pre></div>
<p>the argument to <code>subscribe</code> is an agent, representing a procedure with two arguments; the procedure finds the country at the corresponding coordinates and displays it. The whole agent is "subscribed" to the event type <code>click_event</code> for a
certain button, so that whenever an instance of the event type occurs on that button – because a user has clicked the button – the procedure will be executed with the mouse coordinates being passed as arguments for <code>x</code> and <code>y</code>.
</p><p>The main limitation of Eiffel agents, which distinguishes them from closures in other languages, is that they cannot reference local variables from the enclosing scope. This design decision helps in avoiding ambiguity when talking about a local variable value in a closure - should it be the latest value of the variable or the value captured when the agent is created? Only <code>Current</code> (a reference to current object, analogous to <code>this</code> in Java), its features, and arguments of the agent can be accessed from within the agent body. The values of the outer local variables can be passed by providing additional closed operands to the agent.
</p>
<div class="mw-heading mw-heading3"><h3 id="C++Builder_closure_reserved_word">C++Builder __closure reserved word</h3></div>
<p>Embarcadero C++Builder provides the reserved word <code>__closure</code> to provide a pointer to a method with a similar syntax to a function pointer.<sup id="cite_ref-24" class="reference"><a href="#cite_note-24"><span class="cite-bracket">[</span>22<span class="cite-bracket">]</span></a></sup>
</p><p>
Standard C allows writing a <style data-mw-deduplicate="TemplateStyles:r886049734">
/* start https://en.wikipedia.org/ */


.mw-parser-output .monospaced{font-family:monospace,monospace}


/* end https://en.wikipedia.org/ */
</style><span class="monospaced"><a href="Typedef" title="Typedef">typedef</a></span> for a pointer to a <a href="Function_type" title="Function type">function type</a> using the following syntax:</p><div class="mw-highlight mw-highlight-lang-c++ mw-content-ltr" dir="ltr"><pre><span class="k">typedef</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="p">(</span><span class="o">*</span><span class="n">TMyFunctionPointer</span><span class="p">)(</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="p">);</span>
</pre></div><p>In a similar way, a <span class="monospaced">typedef</span> can be declared for a pointer to a method using this syntax:</p><div class="mw-highlight mw-highlight-lang-c++ mw-content-ltr" dir="ltr"><pre><span class="k">typedef</span><span class="w"> </span><span class="kt">void</span><span class="w"> </span><span class="p">(</span><span class="n">__closure</span><span class="w"> </span><span class="o">*</span><span class="n">TMyMethodPointer</span><span class="p">)();</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1184024115">
/* start https://en.wikipedia.org/ */


.mw-parser-output .div-col{margin-top:0.3em;column-width:30em}.mw-parser-output .div-col-small{font-size:90%}.mw-parser-output .div-col-rules{column-rule:1px solid #aaa}.mw-parser-output .div-col dl,.mw-parser-output .div-col ol,.mw-parser-output .div-col ul{margin-top:0}.mw-parser-output .div-col li,.mw-parser-output .div-col dd{page-break-inside:avoid;break-inside:avoid-column}


/* end https://en.wikipedia.org/ */
</style><div class="div-col">
<ul><li><a href="Command_pattern" title="Command pattern">Command pattern</a></li>
<li><a href="Currying" title="Currying">Currying</a></li>
<li><a href="Lambda_calculus" title="Lambda calculus">Lambda calculus</a></li>
<li><a href="Partial_application" title="Partial application">Partial application</a></li>
<li><a href="Syntactic_closure" title="Syntactic closure">Syntactic closure</a></li>
<li><a href="Value-level_programming" title="Value-level programming">Value-level programming</a></li></ul>
</div>
<div class="mw-heading mw-heading2"><h2 id="Notes">Notes</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */


.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}


/* end https://en.wikipedia.org/ */
</style><div class="reflist reflist-lower-alpha">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text">The function may be stored as a <a href="Reference_(computer_science)" title="Reference (computer science)">reference</a> to a function, such as a <a href="Function_pointer" title="Function pointer">function pointer</a>.</span>
</li>
<li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text">These names usually refer to values, mutable variables, or functions, but can also be other entities such as constants, types, classes, or labels.</span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<div class="reflist reflist-columns references-column-width" style="column-width: 30em;">
<ol class="references">
<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text">Sussman and Steele. "Scheme: An interpreter for extended lambda calculus". "... a data structure containing a lambda expression, and an environment to be used when that lambda expression is applied to arguments." (<a href="https://en.wikisource.org/wiki/Page:Scheme_-_An_interpreter_for_extended_lambda_calculus.djvu/22" class="extiw external" title="s:Page:Scheme - An interpreter for extended lambda calculus.djvu/22">Wikisource</a>)</span>
</li>
<li id="cite_note-dat2012-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-dat2012_4-0">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */


.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}


/* end https://en.wikipedia.org/ */
</style><cite id="CITEREFTurner2012" class="citation conference cs1"><a href="David_A._Turner" class="mw-redirect" title="David A. Turner">Turner, David A.</a> (2012). <a rel="nofollow" class="external text" href="http://www.cs.kent.ac.uk/people/staff/dat/tfp12/tfp12.pdf">"Some History of Functional Programming Languages"</a> <span class="cs1-format">(PDF)</span>. <i>International Symposium on Trends in Functional Programming</i>. Lecture Notes in Computer Science. Vol.&nbsp;7829. Springer. pp.&nbsp;1–20 See 12 §2, note 8 for the claim about M-expressions. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1007%2F978-3-642-40447-4_1">10.1007/978-3-642-40447-4_1</a>. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&nbsp;<bdi>978-3-642-40447-4</bdi>.</cite></span>
</li>
<li id="cite_note-landin-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-landin_5-0">^</a></b></span> <span class="reference-text">
<cite id="CITEREFLandin1964" class="citation journal cs1"><a href="Peter_Landin" title="Peter Landin">Landin, P.J.</a> (January 1964). <a rel="nofollow" class="external text" href="https://academic.oup.com/comjnl/article-pdf/6/4/308/1067901/6-4-308.pdf">"The mechanical evaluation of expressions"</a> <span class="cs1-format">(PDF)</span>. <i>The Computer Journal</i>. <b>6</b> (4): <span class="nowrap">308–</span>320. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1093%2Fcomjnl%2F6.4.308">10.1093/comjnl/6.4.308</a>.</cite></span>
</li>
<li id="cite_note-6"><span class="mw-cite-backlink"><b><a href="#cite_ref-6">^</a></b></span> <span class="reference-text">
<cite id="CITEREFMoses1970" class="citation journal cs1"><a href="Joel_Moses" title="Joel Moses">Moses, Joel</a> (June 1970). "The Function of FUNCTION in LISP, or Why the FUNARG Problem Should Be Called the Environment Problem". <i>ACM SIGSAM Bulletin</i> (15): <span class="nowrap">13–</span>27. <a href="Doi_(identifier)" class="mw-redirect" title="Doi (identifier)">doi</a>:<a rel="nofollow" class="external text" href="https://doi.org/10.1145%2F1093410.1093411">10.1145/1093410.1093411</a>. <a href="Hdl_(identifier)" class="mw-redirect" title="Hdl (identifier)">hdl</a>:<span class="id-lock-free" title="Freely accessible"><a rel="nofollow" class="external text" href="https://hdl.handle.net/1721.1%2F5854">1721.1/5854</a></span>. <a href="S2CID_(identifier)" class="mw-redirect" title="S2CID (identifier)">S2CID</a>&nbsp;<a rel="nofollow" class="external text" href="https://api.semanticscholar.org/CorpusID:17514262">17514262</a>. <a href="AI_Memo" title="AI Memo">AI Memo</a> 199. <q>A useful metaphor for the difference between FUNCTION and QUOTE in LISP is to think of QUOTE as a porous or an open covering of the function since free variables escape to the current environment. FUNCTION acts as a closed or nonporous covering (hence the term "closure" used by Landin). Thus we talk of "open" Lambda expressions (functions in LISP are usually Lambda expressions) and "closed" Lambda expressions. [...] My interest in the environment problem began while Landin, who had a deep understanding of the problem, visited MIT during 1966–67. I then realized the correspondence between the FUNARG lists which are the results of the evaluation of "closed" Lambda expressions in <a href="LISP_1.5" class="mw-redirect" title="LISP 1.5">LISP</a> and <a href="ISWIM" title="ISWIM">ISWIM</a>'s Lambda Closures.</q></cite></span>
</li>
<li id="cite_note-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-7">^</a></b></span> <span class="reference-text"><cite id="CITEREFWikström1987" class="citation book cs1">Wikström, Åke (1987). <i>Functional Programming using Standard ML</i>. Prentice Hall. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&nbsp;<bdi>0-13-331968-7</bdi>. <q>The reason it is called a "closure" is that an expression containing free variables is called an "open" expression, and by associating to it the bindings of its free variables, you close it.</q></cite></span>
</li>
<li id="cite_note-8"><span class="mw-cite-backlink"><b><a href="#cite_ref-8">^</a></b></span> <span class="reference-text"><cite id="CITEREFSussmanSteele1975" class="citation report cs1"><a href="Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman, Gerald Jay</a>; <a href="Guy_L._Steele_Jr." title="Guy L. Steele Jr.">Steele, Guy L. Jr.</a> (December 1975). Scheme: An Interpreter for the Extended Lambda Calculus (Report). <a href="AI_Memo" title="AI Memo">AI Memo</a> 349.</cite></span>
</li>
<li id="cite_note-9"><span class="mw-cite-backlink"><b><a href="#cite_ref-9">^</a></b></span> <span class="reference-text"><cite id="CITEREFAbelsonSussmanSussman1996" class="citation book cs1"><a href="Harold_Abelson" class="mw-redirect" title="Harold Abelson">Abelson, Harold</a>; <a href="Gerald_Jay_Sussman" title="Gerald Jay Sussman">Sussman, Gerald Jay</a>; <a href="Julie_Sussman" class="mw-redirect" title="Julie Sussman">Sussman, Julie</a> (1996). <a rel="nofollow" class="external text" href="https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html"><i>Structure and Interpretation of Computer Programs</i></a>. MIT Press. pp.&nbsp;<span class="nowrap">98–</span>99. <a href="ISBN_(identifier)" class="mw-redirect" title="ISBN (identifier)">ISBN</a>&nbsp;<bdi>0-262-51087-1</bdi>.</cite></span>
</li>
<li id="cite_note-10"><span class="mw-cite-backlink"><b><a href="#cite_ref-10">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/filter">"array.filter"</a>. <i>Mozilla Developer Center</i>. 10 January 2010<span class="reference-accessdate">. Retrieved <span class="nowrap">9 February</span> 2010</span>.</cite></span>
</li>
<li id="cite_note-11"><span class="mw-cite-backlink"><b><a href="#cite_ref-11">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20081226055307/http://okmij.org/ftp/Scheme/oop-in-fp.txt">"Re: FP, OO and relations. Does anyone trump the others?"</a>. 29 December 1999. Archived from <a rel="nofollow" class="external text" href="http://okmij.org/ftp/Scheme/oop-in-fp.txt">the original</a> on 26 December 2008<span class="reference-accessdate">. Retrieved <span class="nowrap">23 December</span> 2008</span>.</cite></span>
</li>
<li id="cite_note-12"><span class="mw-cite-backlink"><b><a href="#cite_ref-12">^</a></b></span> <span class="reference-text"><i><a rel="nofollow" class="external text" href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2550.pdf">Lambda Expressions and Closures</a></i> C++ Standards Committee. 29 February 2008.</span>
</li>
<li id="cite_note-13"><span class="mw-cite-backlink"><b><a href="#cite_ref-13">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html">"6.4 Nested Functions"</a>. <i>GCC Manual</i>. <q>If you try to call the nested function through its address after the containing function exits, all hell breaks loose. If you try to call it after a containing scope level exits, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it's not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.</q></cite></span>
</li>
<li id="cite_note-14"><span class="mw-cite-backlink"><b><a href="#cite_ref-14">^</a></b></span> <span class="reference-text"><i><a rel="nofollow" class="external text" href="https://dspace.mit.edu/handle/1721.1/6935">Foundations of Actor Semantics</a></i> Will Clinger. MIT Mathematics Doctoral Dissertation. June 1981.</span>
</li>
<li id="cite_note-15"><span class="mw-cite-backlink"><b><a href="#cite_ref-15">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind">"Function.prototype.bind()"</a>. <i>MDN Web Docs</i><span class="reference-accessdate">. Retrieved <span class="nowrap">20 November</span> 2018</span>.</cite></span>
</li>
<li id="cite_note-16"><span class="mw-cite-backlink"><b><a href="#cite_ref-16">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Creating_closures_in_loops_A_common_mistake">"Closures"</a>. <i>MDN Web Docs</i><span class="reference-accessdate">. Retrieved <span class="nowrap">20 November</span> 2018</span>.</cite></span>
</li>
<li id="cite_note-17"><span class="mw-cite-backlink"><b><a href="#cite_ref-17">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html">"Nested functions"</a>.</cite></span>
</li>
<li id="cite_note-18"><span class="mw-cite-backlink"><b><a href="#cite_ref-18">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">"Lambda Expressions"</a>. <i>The Java Tutorials</i>.</cite></span>
</li>
<li id="cite_note-19"><span class="mw-cite-backlink"><b><a href="#cite_ref-19">^</a></b></span> <span class="reference-text">
<cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20160831172734/https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top">"Nested, Inner, Member, and Top-Level Classes"</a>. <i>Joseph D. Darcy's Oracle Weblog</i>. July 2007. Archived from <a rel="nofollow" class="external text" href="https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top">the original</a> on 31 August 2016.</cite></span>
</li>
<li id="cite_note-20"><span class="mw-cite-backlink"><b><a href="#cite_ref-20">^</a></b></span> <span class="reference-text">
<cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html">"Inner Class Example"</a>. <i>The Java Tutorials: Learning the Java Language: Classes and Objects</i>.</cite></span>
</li>
<li id="cite_note-21"><span class="mw-cite-backlink"><b><a href="#cite_ref-21">^</a></b></span> <span class="reference-text">
<cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://java.sun.com/docs/books/tutorial/java/javaOO/nested.html">"Nested Classes"</a>. <i>The Java Tutorials: Learning the Java Language: Classes and Objects</i>.</cite></span>
</li>
<li id="cite_note-22"><span class="mw-cite-backlink"><b><a href="#cite_ref-22">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Blocks/Articles/00_Introduction.html">"Blocks Programming Topics"</a>. Apple Inc. 8 March 2011<span class="reference-accessdate">. Retrieved <span class="nowrap">8 March</span> 2011</span>.</cite></span>
</li>
<li id="cite_note-23"><span class="mw-cite-backlink"><b><a href="#cite_ref-23">^</a></b></span> <span class="reference-text"><cite id="CITEREFBengtsson2010" class="citation web cs1">Bengtsson, Joachim (7 July 2010). <a rel="nofollow" class="external text" href="https://web.archive.org/web/20101025034928/http://thirdcog.eu/pwcblocks/">"Programming with C Blocks on Apple Devices"</a>. Archived from <a rel="nofollow" class="external text" href="http://thirdcog.eu/pwcblocks/">the original</a> on 25 October 2010<span class="reference-accessdate">. Retrieved <span class="nowrap">18 September</span> 2010</span>.</cite></span>
</li>
<li id="cite_note-24"><span class="mw-cite-backlink"><b><a href="#cite_ref-24">^</a></b></span> <span class="reference-text">Full documentation can be found at <a rel="nofollow" class="external free" href="http://docwiki.embarcadero.com/RADStudio/Rio/en/Closure">http://docwiki.embarcadero.com/RADStudio/Rio/en/Closure</a></span>
</li>
</ol></div>
<div class="mw-heading mw-heading2"><h2 id="External_links">External links</h2></div>
<ul><li><a rel="nofollow" class="external text" href="https://web.archive.org/web/20160510140804/http://library.readscheme.org/page1.html">Original "Lambda Papers"</a>: A classic series of papers by <a href="Guy_L._Steele_Jr." title="Guy L. Steele Jr.">Guy L. Steele Jr.</a> and <a href="Gerald_Jay_Sussman" title="Gerald Jay Sussman">Gerald Jay Sussman</a> discussing, among other things, the versatility of closures in the context of Scheme (where they appear as <i><a href="Lambda_calculus" title="Lambda calculus">lambda</a> expressions</i>).</li>
<li><cite id="CITEREFGafter2007" class="citation web cs1">Gafter, Neal (28 January 2007). <a rel="nofollow" class="external text" href="https://gafter.blogspot.com/2007/01/definition-of-closures.html">"A Definition of Closures"</a>.</cite></li>
<li><cite id="CITEREFBrachaGafterGoslingvon_der_Ahé" class="citation web cs1"><a href="Gilad_Bracha" title="Gilad Bracha">Bracha, Gilad</a>; Gafter, Neal; <a href="James_Gosling" title="James Gosling">Gosling, James</a>; von der Ahé, Peter. <a rel="nofollow" class="external text" href="http://www.javac.info/closures-v05.html">"Closures for the Java Programming Language (v0.5)"</a>.</cite></li>
<li><a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/Closure.html">Closures</a>: An article about closures in <a href="Dynamic_typing" class="mw-redirect" title="Dynamic typing">dynamically typed</a> imperative languages, by <a href="Martin_Fowler_(software_engineer)" title="Martin Fowler (software engineer)">Martin Fowler</a>.</li>
<li><a rel="nofollow" class="external text" href="http://martinfowler.com/bliki/CollectionClosureMethod.html">Collection closure methods</a>: An example of a technical domain where using closures is convenient, by Martin Fowler.</li></ul></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2025-07-30" href="https://en.wikipedia.org/wiki/?title=Closure_(computer_programming)&amp;oldid=1303428455">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>

</body></html>